﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YuuzleComic.SQLServerDAL;
using YuuzleComic.DBUtility;
using System.Data;
using System.Net;
using System.IO;
using Winista.Text.HtmlParser;
using Winista.Text.HtmlParser.Filters;
using Winista.Text.HtmlParser.Util;
using System.Data.SqlClient;
using YuuzleComic.Common;
using NPinyin;
using System.Text;
using Microsoft.VisualBasic;

public partial class Default2 : YuuzleComic.Web.UI.ManagePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //DataSet ds = DbHelperSQL.Query("select id,mhjs from comics where mhjs like '&nbsp;&nbsp;&nbsp;&nbsp;%'");
        //foreach (DataRow dr in ds.Tables[0].Rows)
        //{
        //    SqlParameter[] parm = new SqlParameter[]{
        //        new SqlParameter("@mhjs", dr["mhjs"].ToString().Replace("&nbsp;&nbsp;&nbsp;&nbsp;","")),
        //        new SqlParameter("@id", dr["id"].ToString())
        //    };
        //    DbHelperSQL.ExecuteSql("update comics set mhjs=@mhjs where id=@id", parm);
        //}
        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //DataSet ds = DbHelperSQL.Query("select * from Collect_News where ParentID<>'' and ParentID is not null and history=1");
        DataSet ds = DbHelperSQL.Query("select b.* from zj a join Collect_News b on a.cjitemid=b.ID where a.tps = b.ImagesCount");
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                WebClient wc = new WebClient();
                string html = "";
                try
                {
                    html = wc.DownloadString(dr["Links"].ToString());
                }
                catch (WebException we)
                {
                    StreamReader sr = new StreamReader(we.Response.GetResponseStream());
                    html = sr.ReadToEnd();
                }

                string content = dr["Content"].ToString();
                Parser parser = Parser.CreateParser(html, "utf-8");
                //AndFilter andFilter = new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "authorcontents"));
                NodeList divList = parser.ExtractAllNodesThatMatch(new TagNameFilter("option"));
                int count = Convert.ToInt32(dr["ImagesCount"]);
                if (divList.Count > count)
                {
                    for (int i = count + 1; i <= divList.Count; i++)
                    {
                        string html1 = "";
                        try
                        {
                            html1 = wc.DownloadString(dr["Links"].ToString() + "&page=" + i);
                        }
                        catch (WebException we)
                        {
                            StreamReader sr = new StreamReader(we.Response.GetResponseStream());
                            html1 = sr.ReadToEnd();
                        }
                        Parser parser1 = Parser.CreateParser(html1, "utf-8");
                        AndFilter andFilter = new AndFilter(new TagNameFilter("img"), new HasAttributeFilter("border", "0"));
                        NodeList divList1 = parser1.ExtractAllNodesThatMatch(andFilter);
                        if (divList1.Count == 3)
                        {
                            string newimg = divList1[0].ToHtml().Replace("..", "http://mh.xindm.cn");
                            if (!content.Contains(newimg))
                            {
                                content += newimg;
                                SqlParameter[] parm = new SqlParameter[]{
                                    new SqlParameter("@Content", content),
                                    new SqlParameter("@ImagesCount", divList.Count),
                                    new SqlParameter("@id", dr["ID"].ToString())
                                };
                                DbHelperSQL.ExecuteSql("update Collect_News set Content=@Content,ImagesCount=@ImagesCount,history=0 where id=@ID", parm);
                            }
                        }
                    }
                }
            }
            Response.Write("修复完毕");
        }
    }

    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        DataSet ds = DbHelperSQL.Query("select b.*,a.id zjid from zj a join Collect_News b on a.cjitemid=b.ID where a.tps < b.ImagesCount");
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                DbHelperSQL.Query("update zj set tps=" + dr["ImagesCount"] + ",tpurl='" + YuuzleComic.Common.Input.GetImagesSrc(dr["Content"].ToString()) + "' where id = " + dr["zjid"]);
            }
        }
        Response.Write("入库完成");
    }

    protected void Cleanup_Click(object sender, EventArgs e)
    {
        this.Clean_Dir(dir.Text.Trim());
        Response.Write("清理完成");
    }

    private void Clean_Dir(string path)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(string.IsNullOrEmpty(path) ? "~/comicdata" : "~/comicdata/" + path));
        bool isdel = DbHelperSQL.Query("select top(1) id from zj where tpadd='" + path + "/'").Tables[0].Rows.Count == 0;
        foreach (FileInfo fileInfo in dirInfo.GetFiles())
        {
            if (isdel || fileInfo.Extension.ToLower()==".rar" || fileInfo.Extension.ToLower()==".zip")
	        {
		        fileInfo.Delete();
	        }
        }
        foreach (DirectoryInfo item in dirInfo.GetDirectories())
        {
            Clean_Dir(string.IsNullOrEmpty(path) ? item.Name : path + "/" + item.Name);
        }
        if (dirInfo.GetDirectories().Length + dirInfo.GetFiles().Length == 0)
        {
            dirInfo.Delete();
        }
    }

    protected void Keyword_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        DataSet ds = DbHelperSQL.Query("select a.mc,b.* from keyword a join comics b on a.cid=b.id");
        sb.AppendLine("Keyword,URL,NoFollow,First Only,New Window,Ignore Case,IsAffiliate,Enable In Comments,Chinese Keyword,Description\n");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.Append("\"" + dr["mc"].ToString().Replace(",", "，") + "\",\"http://www.yzmanga.com/comic/" + dr["id"] + "/\",1,1,1,0,0,0,1,\"" + dr["mc"].ToString() + "\"\n");
        }
        ds = DbHelperSQL.Query("select a.* from zz a join comics b on a.id=b.zzid");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.Append("\"" + dr["zzmc"].ToString().Replace(",", "，") + "\",\"http://www.yzmanga.com/list/author/" + dr["id"] + ".htm\",1,1,1,0,0,0,1,\"" + dr["zzmc"].ToString() + "\"\n");
        }

        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment;filename=wp_weywordlink.export");
        Response.AddHeader("Content-Length", sb.Length.ToString());
        Response.AddHeader("Content-Transfer-Encoding", "binary");
        Response.ContentType = "application/octet-stream";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }

    protected void CreateRSS_Click(object sender, EventArgs e)
    {
        RssChannel channel = new RssChannel();
        channel.Title = "雨泽漫画";
        channel.Description = "雨泽漫画始终努力为漫画迷提供及时的漫画更新和优秀的在线观看体验。在线漫画网,火影忍者NARUTO,海贼王ONEPiece,死神Bleach,网球王子,篮球飞人,神龙之谜,在线看漫画";
        channel.Link = "http://www.yzmanga.com/";
        List<RssItem> items = new List<RssItem>();
        DataSet ds = DbHelperSQL.Query("select top(5000) a.*,b.zzmc from comics a join zz b on a.zzid=b.id order by a.hits");
        // Populate items.
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            RssItem item = new RssItem();
            item.Title = dr["mhmc"].ToString();
            item.Link = "http://www.yzmanga.com/comic/" + dr["id"] + "/";
            item.Author = dr["zzmc"].ToString();
            item.Description = dr["mhjs"].ToString();
            item.PubDate = Convert.ToDateTime(dr["adddate"]);
            items.Add(item);
        }
        YuuzleComic.Common.RssUtil.WriteRSS(channel, items);
        Response.Write("生成rss成功");
    }

    protected void PingXMLRPC_Click(object sender, EventArgs e)
    {
        Blog ehongInfo = new Blog();
        ehongInfo.BlogName = "雨泽漫画";
        ehongInfo.BlogURL = "http://www.yzmanga.com";
        ehongInfo.SiteMap = "http://www.yzmanga.com/web_sitemap_285513ec.xml.gz";
        ehongInfo.SiteRSS = "http://www.yzmanga.com/rss.xml";

        PingXML Baidu = new PingXML();
        Baidu.Url = "http://ping.baidu.com/ping/RPC2";

        PingXML Google = new PingXML();
        Google.Url = "http://blogsearch.google.com/ping/RPC2";

        //List<string> URL = ehongInfo.GetPostURL();
        List<string> URL = new List<string>();
        DataSet ds = DbHelperSQL.Query("select top(100) id from comics order by hits");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            URL.Add("http://www.yzmanga.com/comic/" + dr["id"] + "/");
        }
        foreach (string item in URL)
        {
            Response.Write(string.Format("Ping Baidu With:{0}  Return Value is {1}<br>",
                item, Baidu.BaiduPing(ehongInfo.BlogName, ehongInfo.BlogURL, item, ehongInfo.SiteRSS)));
            Response.Write(string.Format("Ping Google With:{0}  nReturn Value is {1}<br>",
                item, Google.GooglePing(ehongInfo.BlogName, ehongInfo.BlogURL, item, ehongInfo.SiteRSS).message));
        }
    }

    protected void createBM_Click(object sender, EventArgs e)
    {
        DbHelperSQL.ExecuteSql("truncate table search");
        DataSet ds = DbHelperSQL.Query("select a.*,STUFF((SELECT ','+ z.zzmc FROM zz z join comics_zz cz on z.id=cz.zzid where cz.cid=a.id FOR XML PATH('')), 1, 1, '') zzmc from comics a order by a.id desc");
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                List<string> mclist = new List<string>();
                mclist.Add(dr["mhmc"].ToString().Trim());
                if (!string.IsNullOrEmpty(dr["mhbm"].ToString()))
                {
                    string[] bmArr = dr["mhbm"].ToString().Split(',');
                    foreach (string bm in bmArr)
                    {
                        mclist.Add(bm.Trim());
                    }
                }
                foreach (string mc in mclist)
                {
                    SqlParameter[] parameters = {
					new SqlParameter("@cid", SqlDbType.Int),
                    new SqlParameter("@mc1", SqlDbType.VarChar),
                    new SqlParameter("@mc2", SqlDbType.VarChar),
                    new SqlParameter("@mc3", SqlDbType.VarChar),
                    new SqlParameter("@mc4", SqlDbType.VarChar),
                    new SqlParameter("@mc5", SqlDbType.VarChar)};
                    parameters[0].Value = Convert.ToInt32(dr["id"]);
                    parameters[1].Value = mc;
                    parameters[2].Value = Strings.StrConv(mc, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, System.Globalization.CultureInfo.CurrentCulture.LCID);
                    parameters[3].Value = Pinyin.GetPinyin(mc).Replace(" ", "");
                    parameters[4].Value = Pinyin.GetInitials(mc).Replace(" ", "");
                    parameters[5].Value = dr["zzmc"].ToString().Trim();
                    DbHelperSQL.Query("insert into search (cid,mc1,mc2,mc3,mc4,mc5) values(@cid,@mc1,@mc2,@mc3,@mc4,@mc5)", parameters);
                }
            }
        }
        Response.Write("转化拼音完成");
    }

    protected void convertZjTime_Click(object sender, EventArgs e)
    {
        DataSet ds = DbHelperSQL.Query("select id,adddate from zj");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            SqlParameter[] parameters = {
					new SqlParameter("@time", Convert.ToDateTime("1900-01-01").AddDays(Convert.ToInt32(dr["adddate"]) - 2))};
            DbHelperSQL.ExecuteSql("update zj set time=@time where id=" + dr["id"],parameters);
        }
        Response.Write("转化章节时间完成");
    }

    protected void convertMHJS_MHJJ_Click(object sender, EventArgs e)
    {
        DataSet ds = DbHelperSQL.Query("select id,mhjs from comics");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            SqlParameter[] parameters = {
					new SqlParameter("@mhjj", Input.FilterHTML(dr["mhjs"].ToString().Trim()).Trim())};
            DbHelperSQL.ExecuteSql("update comics set mhjj=left(@mhjj,300) where id=" + dr["id"], parameters);
        }
        Response.Write("转化漫画简介完成");
    }
}